package com.tz.online.book.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.tz.online.book.dao.IBookDao;
import com.tz.online.entity.Book;
import com.tz.online.util.HibernateCallback;
import com.tz.online.util.HibernateTemplate;

public class BookDaoImpl implements IBookDao {

	private HibernateTemplate template = new HibernateTemplate();
	
	/*****
	 * 按分类进行查询
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Book> selectByCondition(int now, int size, String cate) {
		//通过模板来执行
		return (List<Book>) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				Criteria c = ses.createCriteria(Book.class,"b");
				//
				if(cate != null && cate.trim().length() > 0) {
					c.createAlias("b.category", "c")
						.add(Restrictions.eq("c.name", cate));
				}
				//返回
				return c.addOrder(Order.asc("b.id"))
							.setFirstResult((now-1)*size)
							.setMaxResults(size)
							.setCacheable(true)
							.list();
			}
		});
	}
	

	@Override
	public Book findById(Long id) {
		//
		return (Book) template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses.get(Book.class, id);
			}
		});
	}


	@Override
	public int rowCount(String cate) {
		//
		Long count = (Long)template.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				Criteria c = ses.createCriteria(Book.class,"b"); 
				//判断
				if(cate != null) {
					c.createAlias("b.category", "c")
						.add(Restrictions.eq("c.name", cate));
				}
				//返回
				return c.setProjection(Projections.rowCount())
						.setCacheable(true)
						.uniqueResult();
			}
		});
		return count.intValue(); 
	}

}
